import { fetchSubProjects, fetchSubProjectEmployees } from '../../../api/project';
import {addTravelRecord,uploadVoucher} from '../../../api/travel';

Page({
  data: {
    projectId: null, // 大项目ID
    projectName: '', // 大项目名称
    subProjects: [], // 小项目列表
    employees: [], // 员工列表
    subProjectId: null, // 选中的小项目ID
    subprojectName:'',
    employeeId: null, // 选中的员工ID
    startTime: '', // 起始日期
    endTime: '', // 结束日期
    departure: '', // 出发地
    destination: '', // 目的地
    kilometers: '', // 公里数
    image: '', // 凭证图片名称
    voucherFileName: '', // 凭证图片路径
    employeeName: '' // 选中的员工名称
  },

  onLoad(options) {
    // 从传入的参数中获取大项目ID和名称，并初始化页面数据
    const { projectId, projectName } = options;
    this.setData({ projectId, projectName });
    this.fetchSubProjects(projectId);
  },

  // 获取小项目列表
  fetchSubProjects(projectId) {
    fetchSubProjects(projectId).then(response => {
      if (response.code === 1) {
        console.log(response);
        this.setData({ subProjects: response.data });
      } else {
        console.error('Failed to fetch sub-projects');
      }
    }).catch(error => {
      console.error('Error fetching sub-projects:', error);
    });
  },

  // 获取指定小项目的员工列表
  fetchSubProjectEmployees(subProjectId) {
    fetchSubProjectEmployees(subProjectId).then(response => {
      if (response.code === 1) {
        console.log(response);
        this.setData({ employees: response.data });
      } else {
        console.error('Failed to fetch employees');
      }
    }).catch(error => {
      console.error('Error fetching employees:', error);
    });
  },

  // 当选择小项目时，更新小项目ID和名称，并获取相应的员工列表
  onSubProjectChange(event) {
    const subProjectIndex = event.detail.value;
    const subProjectId = this.data.subProjects[subProjectIndex].id;
    const subprojectName = this.data.subProjects[subProjectIndex].name;
    this.setData({ subProjectId, subprojectName });
    console.log(subprojectName);
    this.fetchSubProjectEmployees(subProjectId);
  },

  // 当选择员工时，更新员工ID和名称
  onEmployeeChange(event) {
    const employeeIndex = event.detail.value;
    const employeeId = this.data.employees[employeeIndex].employeeId;
    const employeeName = this.data.employees[employeeIndex].name;
    this.setData({ employeeId, employeeName });
  },

  // 更新日期字段
  onDateChange(event) {
    const type = event.currentTarget.dataset.type;
    const value = event.detail.value;
    this.setData({ [type]: value });
  },

  // 更新输入字段
  onInputChange(event) {
    const { id } = event.currentTarget.dataset;
    const value = event.detail.value;
    this.setData({ [id]: value });
  },
  // 上传凭证图片
  uploadVoucher() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: res => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        const fileName = tempFilePath.split('/').pop(); // 提取文件名
        this.setData({ voucherFileName: tempFilePath }); // 预览图片
        uploadVoucher(tempFilePath).then(response => {
          if (response.code === 1) {
            console.log(response);
            this.setData({ image: response.data }); // 保存文件名
          } else {
            console.error('Failed to upload voucher');
          }
        }).catch(error => {
          console.error('Error uploading voucher:', error);
        });
      }
    });
  },
  // 提交表单
  submitForm() {
    const { projectId, subprojectName, employeeId, startTime, endTime, departure, destination, kilometers, image } = this.data;

    // 检查是否所有字段都已填写
    if (!subprojectName) {
      wx.showToast({ title: '请选择小项目', icon: 'none' });
      return;
    }
    if (!employeeId) {
      wx.showToast({ title: '请选择员工', icon: 'none' });
      return;
    }
    if (!startTime) {
      wx.showToast({ title: '请选择起始日期', icon: 'none' });
      return;
    }
    if (!endTime) {
      wx.showToast({ title: '请选择结束日期', icon: 'none' });
      return;
    }
    if (!departure) {
      wx.showToast({ title: '请输入出发地', icon: 'none' });
      return;
    }
    if (!destination) {
      wx.showToast({ title: '请输入目的地', icon: 'none' });
      return;
    }
    if (!kilometers) {
      wx.showToast({ title: '请输入公里数', icon: 'none' });
      return;
    }

    // 提交表单数据到后端
    addTravelRecord({ projectId, subprojectName, employeeId, startTime, endTime, departure, destination, kilometers, image }).then(response => {
      if (response.code === 1) {
        console.log(response);
        wx.showToast({ title: '提交成功', icon: 'success' });
        wx.navigateBack();
      } else {
        wx.showToast({ title: '提交失败，请重试', icon: 'none' });
        console.error('Failed to submit travel record');
      }
    }).catch(error => {
      wx.showToast({ title: '提交失败，请重试', icon: 'none' });
      console.error('Error submitting travel record:', error);
    });
  }
});